<?php

declare(strict_types=1);

namespace Tool\Database;

use Exception;
use Tool\Database\MockType\Date;
use Tool\Database\MockType\Decimal;
use Tool\Database\MockType\Integer;
use Tool\Database\MockType\None;
use Tool\Database\MockType\Varchar;
use Tool\Database\MockType\VarcharName;
use Tool\Database\MockType\VarcharPhone;

/**
 * 字段工厂.
 */
class ColumnFactory
{
    private static array $class = [
        None::class,
        Integer::class,
        Decimal::class,
        Varchar::class,
        Date::class,
        VarcharName::class,
        VarcharPhone::class,
    ];

    /**
     * 获取类名.
     *
     * @param mixed $defaultIndex
     */
    public static function getClassName(string $index, $defaultIndex): ?string
    {
        if ('' === $index) {
            $index = $defaultIndex;
        }

        return static::$class[$index] ?? null;
    }

    /**
     * 获取默认类.
     */
    public static function getDefaultClass(string $dataType): string
    {
        switch ($dataType) {
            case 'tinyint':
            case 'smallint':
            case 'mediumint':
            case 'int':
            case 'integer':
            case 'bigint':
                return '1';

            case 'double':
            case 'real':
            case 'float':
            case 'decimal':
            case 'numeric':
                return '2';

            case 'char':
            case 'varchar':
            case 'tinytext':
            case 'text':
            case 'mediumtext':
            case 'longtext':
                return '3';

            case 'date':
            case 'time':
            case 'year':
            case 'timestamp':
            case 'datetime':
                return '4';

            case 'bit':
            case 'tinyblob':
            case 'blob':
            case 'mediumblob':
            case 'longblob':
            case 'binary':
            case 'varbinary':
                return '0';

            case 'enum':
            case 'set':
                return '0';

            case 'point':
            case 'linestring':
            case 'polygon':
            case 'geometry':
            case 'multipoint':
            case 'multilinestring':
            case 'multipolygon':
            case 'geometrycollection':
                return '0';

            default:
                throw new Exception('unknown column type');
        }
    }

    /**
     * 获取类列表.
     */
    public static function getClassList(): array
    {
        $rest = [];
        foreach (static::$class as $className) {
            $list = explode('\\', $className);
            $rest[] = array_pop($list);
        }

        return $rest;
    }
}
